package com.acwer.drgs.performance.task;

import com.acwer.common.RpnMsg;
import com.acwer.dao.domain.DrgStd;
import com.acwer.dao.domain.DrgStd3;
import com.acwer.dao.mapper.DrgStdMapper;
import com.acwer.dao.mapper.DrgStdMapper3;
import com.acwer.dao.mapper.MiniPfmMapper;
import com.acwer.drgs.performance.config.ApplicationValues;
import com.acwer.drgs.performance.config.HttpUtils;
import com.acwer.drgs.performance.controller.ApiController;
import com.acwer.drgs.performance.domain.RqGrp;
import com.acwer.drgs.performance.es.domain.MiniPerformanceInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.beanutils.BeanUtils;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Component
public class MyTask {

    @Autowired
    DrgStdMapper drgStdMapper;

    @Autowired
    DrgStdMapper3 drgStdMapper3;

    List<DrgStd> drgStds;
    List<DrgStd3> drgStd3s;


    @Autowired
    MiniPfmMapper miniPfmMapper;

//    @Autowired
//    ApiController apiController;

    @Autowired
    RestHighLevelClient client;

    @Scheduled(cron="0/5 * * * * ?")
    public void syncData(){
        QueryWrapper<DrgStd> query=new QueryWrapper<>();
        query.eq("版本","CHSDRG");

        QueryWrapper<DrgStd3> query3=new QueryWrapper<>();
        query3.eq("版本","CHSDRG");

        if(drgStds==null){
            drgStds = drgStdMapper.selectList(query);
        }

        if(drgStd3s==null){
            drgStd3s=drgStdMapper3.selectList(query3);
        }

        List<Map<String, Object>> ls = miniPfmMapper.select();
        BulkRequest bulkRequest=new BulkRequest();

        Map<String, String> inGrpMap = new HashMap<String, String>(){
            {
                // 外科
                put("wk", ".[a-j].*");
                // 操作
                put("cz", ".[k-q].*");
                // 内科
                put("nk", ".[r-z].*");
            }
        };

        List<String> ids=new ArrayList<>();

        for (Map<String, Object> mm : ls) {
            Map<String,Object>nm= ApiController.keyToLowerCase(mm);
            nm.put("@timestamp",new Date());

            MiniPerformanceInfo info=new MiniPerformanceInfo();
            try {
                BeanUtils.populate(info, nm);

            }catch (Exception ex){}
            ids.add(info.getId());

            try {
                MiniPerformanceInfo.GrpInfo grp = grp(info);
                boolean f=!StringUtils.isEmpty(grp.getMdc())&&grp.getMdc().startsWith("MDC");
                nm.put("ingrp",f);

                String code = grp.getDrg();
                double benchmarkFee=0;
                double benchmarkStayDays=0;
                double weight=0;
                if(!StringUtils.isEmpty(code)){
                    List<DrgStd> tmpDrgStd1 = drgStds.stream().filter(it -> it.get分组编码().equals(code)).collect(Collectors.toList());
                    List<DrgStd3> tmpDrgStd2 = drgStd3s.stream().filter(it -> it.get分组编码().equals(code)).collect(Collectors.toList());

                    benchmarkFee=tmpDrgStd2.get(0).get平均费用();
                    benchmarkStayDays=tmpDrgStd2.get(0).get平均床日();
                    weight=tmpDrgStd2.get(0).get权重();
                    grp.setBenchmarkFee(benchmarkFee);
                    grp.setBenchmarkStayDays(benchmarkStayDays);
                    grp.setWeight(weight);
                    JSONObject o = (JSONObject) JSON.toJSON(grp);
                    if(f){
                        o.put("costratio",info.getZfy()/benchmarkFee);
                        o.put("bedratio",Double.parseDouble(info.getSjzyts())/benchmarkStayDays);
                        for (Map.Entry<String, String> entry : inGrpMap.entrySet()) {
                            if(Pattern.matches("(?i)"+entry.getValue(), grp.getDrg())){
                                o.put("drgingrptype",entry.getKey());
                                break;
                            }
                        }
                        nm.put("grpinfo",o);
                    }

                }else{
                    JSONObject o = (JSONObject)JSON.toJSON(grp);
                    nm.put("grpinfo",o);
                }

                IndexRequest request=new IndexRequest("minipfm-stream")
                        .source(nm)
                        .opType(DocWriteRequest.OpType.CREATE);
                bulkRequest.add(request);

            }catch (Exception ee){
                ee.printStackTrace();
                nm.put("ingrp",false);
                IndexRequest request=new IndexRequest("minipfm-stream")
                        .source(nm)
                        .opType(DocWriteRequest.OpType.CREATE);
                bulkRequest.add(request);
            }

        }
        if(ids.size()>0){
            try {

                BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);

                miniPfmMapper.updateById(ids);
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }

    @Autowired
    ApplicationValues applicationValues;

    HttpUtils httpUtils = new HttpUtils();

    public MiniPerformanceInfo.GrpInfo grp(MiniPerformanceInfo info){

        RqGrp rqGrp=new RqGrp();
        //主要诊断
        rqGrp.setMDCode(info.getJbdm());
        //其他诊断编码
        rqGrp.setODCodes(new ArrayList<String>(){
                             {   if(info.getJbdm1()!=null){
                                 add(info.getJbdm1());
                             }
                                 if(info.getJbdm2()!=null){
                                     add(info.getJbdm2());
                                 }
                                 if(info.getJbdm3()!=null){
                                     add(info.getJbdm3());
                                 }
                                 if(info.getJbdm4()!=null){
                                     add(info.getJbdm4());
                                 }
                                 if(info.getJbdm5()!=null){
                                     add(info.getJbdm5());
                                 }
                                 if(info.getJbdm6()!=null){
                                     add(info.getJbdm6());
                                 }
                                 if(info.getJbdm7()!=null){
                                     add(info.getJbdm7());
                                 }
                                 if(info.getJbdm8()!=null){
                                     add(info.getJbdm8());
                                 }
                                 if(info.getJbdm9()!=null){
                                     add(info.getJbdm9());
                                 }
                                 if(info.getJbdm10()!=null){
                                     add(info.getJbdm10());
                                 }
                                 if(info.getJbdm11()!=null){

                                     add(info.getJbdm11());
                                 }
                                 if(info.getJbdm12()!=null){
                                     add(info.getJbdm12());
                                 }
                                 if(info.getJbdm13()!=null){
                                     add(info.getJbdm13());
                                 }
                                 if(info.getJbdm14()!=null){
                                     add(info.getJbdm14());
                                 }
                                 if(info.getJbdm15()!=null){
                                     add(info.getJbdm15());
                                 }
                             }
                         }
        );
        //主手术编码
        rqGrp.setMOpCode(info.getSsjczbm1());
        rqGrp.setOpCodes(new ArrayList<String>(){
            {
                if (info.getSsjczbm1()!=null) {

                    add(info.getSsjczbm1());

                }
                if (info.getSsjczbm2()!=null) {

                    add(info.getSsjczbm2());
                }

                if (info.getSsjczbm3()!=null) {

                    add(info.getSsjczbm3());
                }

                if (info.getSsjczbm4()!=null) {

                    add(info.getSsjczbm4());
                }

                if (info.getSsjczbm5()!=null) {

                    add(info.getSsjczbm5());
                }

                if (info.getSsjczbm6()!=null) {

                    add(info.getSsjczbm6());
                }

                if (info.getSsjczbm7()!=null) {

                    add(info.getSsjczbm7());
                }

            }
        });
        rqGrp.setAge(info.getNl());
        rqGrp.setGender(Integer.parseInt(info.getXb()));
        rqGrp.setAmount(info.getZfy());

        rqGrp.setBah(info.getBah());
        if(!StringUtils.isEmpty(info.getXsecstz())){
            rqGrp.setNeoWeight(info.getXsecstz().toString());
        }
        if(!StringUtils.isEmpty(info.getXserytz())){
            rqGrp.setNeoHosptWeight(info.getXserytz().toString());
        }

        rqGrp.setLenOfStasy(Double.parseDouble(info.getSjzyts()));
        rqGrp.setLeaveWay(Integer.parseInt(info.getLyfs()));
        rqGrp.setIcd9Edition("1");
        rqGrp.setIcd10Edition("1");
        rqGrp.setDrgEdtion("CHSDRG");
        rqGrp.setUserName(info.getUsername());
        rqGrp.setBah(info.getBah());
        rqGrp.setGender(Integer.parseInt(info.getXb()));
        rqGrp.setUserName(info.getUsername());
        rqGrp.setMDCode(info.getJbdm());
        String jsonStr= JSON.toJSONString(rqGrp);
        System.out.println("jsonstr:"+jsonStr);
        RpnMsg rpnMsg1 =httpUtils.sendPost(jsonStr, applicationValues.getUri());

        try {
            MiniPerformanceInfo.GrpInfo info1=new MiniPerformanceInfo.GrpInfo();
            BeanUtils.populate(info1, (Map<String, ? extends Object>) rpnMsg1.getData());
            return info1;
        }catch (Exception ex){
            return null;
        }
        //return null;
    }
}
